import os

import numpy as np
import xarray as xr

from ppgnss import gnss_io
from ppgnss import gnss_time
from ppgnss import gnss_utils

gim_dir = "/Users/lzhang/research/TEC_forcast/data/GIM"
gim_dir = "../data/GIM"
out_dir = "data"
time_list = list()
data_list = list()
year_from, doy_from = 2018, 1
year_to, doy_to = 2019, 1
jd_from = gnss_time.doy2jd(year_from, doy_from)
jd_to = gnss_time.doy2jd(year_to, doy_to)
ndays = int(jd_to - jd_from)
dataset = np.zeros((ndays*24, 71, 73))
iday = 0
for year in range(year_from, year_to):
    days_in_year = gnss_time.total_days(year)
    for doy in range(1, days_in_year+1):
        fn = os.path.join(gim_dir, "CODG%03d0.%02dI" %(doy, year-2000))
        print(fn)
        xr_gim = gnss_io.read_ionex_file(fn)
        dataset[iday*24:(iday+1)*24] = xr_gim.values[:24, :, :]
        iday += 1
        time_list.extend(xr_gim.coords["time"].values[:24])
xr_data = xr.DataArray(dataset, coords={"time": time_list,
                                        "lat": xr_gim.coords["lat"].values,
                                        "lon": xr_gim.coords["lon"]})
outfilename = os.path.join(out_dir, "gim%04d_%04d.obj" %(year_from, year_to))
gnss_utils.saveobject(xr_data, outfilename)
print(outfilename + " is saved!")